﻿using JX.Application;
using JX.Core.Entity;
using JX.Infrastructure;
using JX.Infrastructure.Common;
using JX.Infrastructure.Field;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace JXWebSite.Components
{
	/// <summary>
	/// 模型字段视图组件
	/// </summary>
	[ViewComponent(Name = "FieldControl")]
	public class FieldControlViewComponent : ViewComponent
	{
		private readonly IUserGroupsServiceAppDapper _userGroupsServiceApp;
		private readonly IRolesServiceAppDapper _rolesServiceApp;
		private readonly IModelsServiceAppDapper _ModelsService;
		private readonly INodesServiceAppDapper _NodesService;
		private readonly ICommonInfoServiceAppDapper _CommonInfoService;
		private readonly IFlowProcessServiceAppDapper _FlowProcessService;
		/// <summary>
		/// 依赖注入
		/// </summary>
		/// <param name="userGroupsServiceApp"></param>
		/// <param name="rolesServiceApp"></param>
		/// <param name="NodesService"></param>
		/// <param name="ModelsService"></param>
		/// <param name="CommonInfoService"></param>
		/// <param name="FlowProcessService"></param>
		public FieldControlViewComponent(IUserGroupsServiceAppDapper userGroupsServiceApp,
			IRolesServiceAppDapper rolesServiceApp,
			INodesServiceAppDapper NodesService,
			IModelsServiceAppDapper ModelsService,
			ICommonInfoServiceAppDapper CommonInfoService,
			IFlowProcessServiceAppDapper FlowProcessService)
		{
			_userGroupsServiceApp = userGroupsServiceApp;
			_rolesServiceApp = rolesServiceApp;
			_ModelsService = ModelsService;
			_NodesService = NodesService;
			_CommonInfoService = CommonInfoService;
			_FlowProcessService = FlowProcessService;
		}
		/// <summary>
		/// 异步调用
		/// </summary>
		/// <param name="viewModel"></param>
		/// <returns></returns>
		public async Task<IViewComponentResult> InvokeAsync(FieldControlViewModel viewModel =null)
		{
			viewModel = await GetViewModelAsync(viewModel);
			return View(viewModel);
		}

		private async Task<FieldControlViewModel> GetViewModelAsync(FieldControlViewModel viewModel)
		{
			if (viewModel == null)
			{
				viewModel = new FieldControlViewModel();
			}
			if (viewModel.IsAdminManage)
			{
				viewModel.IsShow = await _rolesServiceApp.AccessCheckFieldPermission(OperateCode.ContentFieldInput, viewModel.ModelID, viewModel.FieldName);
			}
			else
			{
				viewModel.IsShow = await _userGroupsServiceApp.AccessCheckFieldPermission(OperateCode.ContentFieldInput, viewModel.ModelID, viewModel.FieldName);
			}
			if (viewModel.Disabled)
			{
				viewModel.IsShow = false;
				return viewModel;
			}
			//准备字段控件的字段值
			if (viewModel.DataSource.Rows.Count > 0)
			{
				switch (viewModel.FieldType)
				{
					case FieldType.RegionType:
						viewModel.FieldValue = InitRegionTypeValue(viewModel.DataSource.Rows[0][viewModel.FieldName + "_Country"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Province"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_City"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area"].ToString(), viewModel.Settings[2], DataConverter.CLng(viewModel.Settings[1], 5));
						break;
					case FieldType.RegionTypeFive:
						viewModel.FieldValue = InitRegionFiveTypeValue(viewModel.DataSource.Rows[0][viewModel.FieldName + "_Country"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Province"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_City"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area1"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area2"].ToString(), viewModel.Settings[2], DataConverter.CLng(viewModel.Settings[1], 2));
						break;
					case FieldType.RegionTypeText:
						viewModel.FieldValue = InitRegionTypeTextValue(viewModel.DataSource.Rows[0][viewModel.FieldName + "_Country"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Province"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_City"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Address"].ToString(), viewModel.Settings[2], DataConverter.CLng(viewModel.Settings[1], 5));
						break;
					case FieldType.FileType:
						if (DataConverter.CBoolean(viewModel.Settings[3]))
						{
							viewModel.Tips = DataConverter.ToString(viewModel.DataSource.Rows[0][viewModel.Settings[4]]);
						}
						break;
				}
				if (viewModel.FieldType != FieldType.ValidateCodeType
					&& viewModel.FieldType != FieldType.RegionType
					&& viewModel.FieldType != FieldType.RegionTypeFive
					&& viewModel.FieldType != FieldType.RegionTypeText
					&& viewModel.DataSource.Columns.Contains(viewModel.FieldName))
				{
					viewModel.FieldValue = DataConverter.ToString(viewModel.DataSource.Rows[0][viewModel.FieldName]);
				}
			}
			//为需要数据源的字段控件准备选项数据
			switch (viewModel.FieldType)
			{
				case FieldType.NodeType:
				case FieldType.NodeCategory:
				case FieldType.InfoType:
					string nodeJsonData = string.Empty;
					var nodeList = _NodesService.GetNodeNameForContainerItems(true);
					nodeList.ToList().ForEach(item =>
					{
						nodeJsonData += "{id:'" + item.NodeID + "',text:'" + item.NodeName + "'},";
					});
					nodeJsonData = nodeJsonData.TrimEnd(',');
					nodeJsonData = "[" + nodeJsonData + "]";
					viewModel.Tips = nodeJsonData;
					break;
				case FieldType.LookType:
					int modelID = DataConverter.CLng(viewModel.Settings[0]);
					string fieldName = viewModel.Settings[1];
					var modelEntity = _ModelsService.Get(modelID);
					var fieldEntity = _ModelsService.GetFieldInfoByFieldName(modelID, fieldName);
					string tableName;
					if(fieldEntity.FieldLevel == 0)
					{
						tableName = "CommonInfo";
					}
					else
					{
						tableName = modelEntity.TableName;
					}
					string jsonData = string.Empty;
					IList<string> fieldValueList = _ModelsService.GetLookupField(tableName, fieldName, modelID);
					fieldValueList.ToList().ForEach(item =>
					{
						jsonData += "{id:'" + item + "',text:'" + item + "'},";
					});
					jsonData = jsonData.TrimEnd(',');
					jsonData = "[" + jsonData + "]";
					viewModel.Tips = jsonData;
					break;
				case FieldType.ListBoxDataType:
					string strSQL = viewModel.Settings[0];
					string strTextField = viewModel.Settings[1].Trim();
					string strValueField = viewModel.Settings[2].Trim();
					var dtListBoxData = _ModelsService.GetDataTableBySql(strSQL);
					string jsonListBoxData = string.Empty;
					foreach (DataRow row in dtListBoxData.Rows)
					{
						jsonListBoxData += "{id:'" + row[strValueField] + "',text:'" + row[strTextField] + "'},";
					}
					jsonListBoxData = jsonListBoxData.TrimEnd(',');
					jsonListBoxData = "[" + jsonListBoxData + "]";
					viewModel.Tips = jsonListBoxData;
					break;
				case FieldType.StatusType:
					string jsonStatusData = string.Empty;
					string selectValue = string.Empty;
					int nodeId = Utility.Request("NodeID", 0);
					int GID = Utility.Request("GID", 0);
					if (nodeId == 0)
					{
						var commonInfoEntity = _CommonInfoService.Get(GID);
						if(commonInfoEntity != null)
						{
							nodeId = commonInfoEntity.NodeID.ToInt32();
						}
					}
					if (viewModel.IsAdminManage)
					{
						#region 后台管理页面
						int nodeWorkFlowId = _NodesService.GetNodeWorkFlowId(nodeId);
						string roles = MyHttpContext.CurrentRoleID;
						var flowProcessByRoles = _FlowProcessService.GetFlowProcessByRoles(nodeWorkFlowId, roles);
						if(GID > 0)
						{
							#region 修改
							jsonStatusData = "{id:'"+ viewModel.FieldValue + "',text:'不改变当前状态'},";
							selectValue = viewModel.FieldValue;
							if (MyHttpContext.IsSuperAdmin || (nodeWorkFlowId == -1))
							{
								if (viewModel.FieldValue == "99")
								{
									jsonStatusData = "{id:'0',text:'待审核'},{id:'99',text:'终审通过'},";
									selectValue = "99";
								}
								else
								{
									jsonStatusData += "{id:'99',text:'终审通过'},";
								}
							}
							else if (flowProcessByRoles != null)
							{
								string strReject = "{id:'" + flowProcessByRoles.RejectActionStatus.ToString() + "',text:'" + flowProcessByRoles.RejectActionName + "'},";
								string strPass = "{id:'" + flowProcessByRoles.PassActionStatus.ToString() + "',text:'" + flowProcessByRoles.PassActionName + "'},";
								if (viewModel.FieldValue == flowProcessByRoles.PassActionStatus.ToString())
								{
									jsonStatusData = strReject + strPass;
								}
								else
								{
									jsonStatusData = strReject + jsonStatusData + strPass;
								}
							}
							#endregion
						}
						else
						{
							#region 添加
							jsonStatusData = "{id:'0',text:'待审核'},";
							selectValue = "0";
							if (MyHttpContext.IsSuperAdmin || (nodeWorkFlowId == -1))
							{
								jsonStatusData += "{id:'99',text:'终审通过'},";
								selectValue = "99";
							}
							else if (flowProcessByRoles != null)
							{
								jsonStatusData += "{id:'"+ flowProcessByRoles.PassActionStatus.ToString() + "',text:'"+ flowProcessByRoles.PassActionName + "'},";
								selectValue = flowProcessByRoles.PassActionStatus.ToString();
							}
							#endregion
						}
						#endregion
					}
					else
					{
						jsonStatusData = "{id:'0',text:'待审核'},";
						selectValue = "0";
					}
					jsonStatusData = jsonStatusData.TrimEnd(',');
					jsonStatusData = "[" + jsonStatusData + "]";
					viewModel.Tips = jsonStatusData;
					viewModel.FieldValue = selectValue;
					break;
			}
			
			return viewModel;
		}

		/// <summary>
		/// 初始化区域类型控件的字段值
		/// </summary>
		/// <param name="fieldValue">字段值</param>
		/// <param name="defaultValue">默认值</param>
		/// <param name="mode">显示类型(1：国家+省；2：国家+省+市；3：国家+省+市+县；4：省+市；5：省+市+县；6：市+县；)</param>
		/// <returns></returns>
		private string InitRegionTypeValue(string fieldValue, string defaultValue, int mode)
		{
			string str = "";
			string[] strArray = fieldValue.Split(new char[] { ',' });
			string[] strArray2 = defaultValue.Split(new char[] { ',' });
			if ((mode == 6) || (mode == 5) || (mode == 4))
			{
				if (string.IsNullOrEmpty(strArray[0]))
				{
					strArray[0] = strArray2[0];
				}
				if ((mode == 6) && string.IsNullOrEmpty(strArray[1]))
				{
					strArray[1] = strArray2[1];
				}
			}
			for (int i = 0; i < 4; i++)
			{
				str = str + strArray[i] + ",";
			}
			return str.Remove(str.Length - 1);
		}
		/// <summary>
		/// 初始化区域(5级)类型控件的字段值
		/// </summary>
		/// <param name="fieldValue">字段值</param>
		/// <param name="defaultValue">默认值</param>
		/// <param name="mode">显示类型(1：国家+省+市+县+街道+小区；2：省+市+县+街道+小区；3：市+县+街道+小区；)</param>
		/// <returns></returns>
		private string InitRegionFiveTypeValue(string fieldValue, string defaultValue, int mode)
		{
			string str = "";
			string[] strArray = fieldValue.Split(new char[] { ',' });
			string[] strArray2 = defaultValue.Split(new char[] { ',' });
			if (string.IsNullOrEmpty(strArray[0]))
			{
				strArray[0] = strArray2[0];
			}
			if ((mode == 3) && string.IsNullOrEmpty(strArray[1]))
			{
				strArray[1] = strArray2[1];
			}
			for (int i = 0; i < 6; i++)
			{
				str = str + strArray[i] + ",";
			}
			return str.Remove(str.Length - 1);
		}
		/// <summary>
		/// 初始化区域类型控件的字段值
		/// </summary>
		/// <param name="fieldValue">字段值</param>
		/// <param name="defaultValue">默认值</param>
		/// <param name="mode">显示类型(1：国家+省；2：国家+省+市；3：国家+省+市+县；4：省+市；5：省+市+县；6：市+县；)</param>
		/// <returns></returns>
		private string InitRegionTypeTextValue(string fieldValue, string defaultValue, int mode)
		{
			string str = "";
			string[] strArray = fieldValue.Split(new char[] { ',' });
			string[] strArray2 = defaultValue.Split(new char[] { ',' });
			if ((mode == 6) || (mode == 5) || (mode == 4))
			{
				if (string.IsNullOrEmpty(strArray[0]))
				{
					strArray[0] = strArray2[0];
				}
				if ((mode == 6) && string.IsNullOrEmpty(strArray[1]))
				{
					strArray[1] = strArray2[1];
				}
			}
			for (int i = 0; i < 5; i++)
			{
				str = str + strArray[i] + ",";
			}
			return str.Remove(str.Length - 1);
		}
	}
}
